package com.probox.modules.controller.order;

import cn.hutool.core.util.ObjectUtil;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.PlatSourceEnum;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.core.utils.poi.ExcelUtil;
import com.probox.common.core.web.controller.BaseController;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.core.web.page.TableDataInfo;
import com.probox.common.entity.domain.order.*;
import com.probox.common.entity.domain.order.vo.OrderSettlementVo;
import com.probox.common.entity.domain.platfom.PlatformStoreGroup;
import com.probox.common.entity.service.order.IOrderInfoItemService;
import com.probox.common.entity.service.order.IOrderInfoService;
import com.probox.common.entity.service.platfom.IPlatformStoreGroupService;
import com.probox.common.entity.service.system.ISysUserService;
import com.probox.common.log.annotation.Log;
import com.probox.common.log.enums.BusinessType;
import com.probox.common.security.annotation.PreAuthorize;
import com.probox.order.api.domain.OrderQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单子Controller
 *
 * @author usoft
 * @date 2021-05-27
 */
@RestController
@RequestMapping("/order/info")
public class OrderInfoController extends BaseController {
    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IPlatformStoreGroupService storeGroupService;

    @Autowired
    private IOrderInfoItemService orderInfoItemService;


    /**
     * 查询订单子列表
     */
    @PreAuthorize(hasPermi = "order:info:list")
    @GetMapping("/list")
    public TableDataInfo list(OrderInfo orderInfo) {

        startPage();
        List<OrderInfo> list = orderInfoService.queryList(orderInfo);
        return getDataTable(list);
    }

    /**
     * 合计现金收入
     * @param orderInfo
     * @return
     */
    @PreAuthorize(hasPermi = "order:info:list")
    @GetMapping("/sumList")
    public AjaxResult sumList(OrderInfo orderInfo) {
        if(ObjectUtil.isEmpty(orderInfo.getStoreId())){
            orderInfo.setStoreId(SecurityUtils.getStoreId());
        }else{
            List<Long> stores = sysUserService.getUserStores(SecurityUtils.getUserId());
            if (stores != null) {
                if (orderInfo.getStoreIds() == null) {
                    orderInfo.setStoreIds(stores);
                } else {
                    orderInfo.getStoreIds().addAll(stores);
                }
            }
        }
        if (orderInfo.getStoreId() != null){
            if (orderInfo.getStoreIds() == null){
                orderInfo.setStoreIds(new ArrayList<>());
            }
            orderInfo.getStoreIds().add(orderInfo.getStoreId());
        }
        if (orderInfo.getStoreIds() == null || orderInfo.getStoreIds().size()==0){
            if (orderInfo.getStoreGroupId() != null){
                PlatformStoreGroup group = storeGroupService.getById(orderInfo.getStoreGroupId());
                if (group != null && StringUtils.isNotEmpty(group.getStoreIds())){
                    List<Long> ids = new ArrayList<>();
                    String[] storeIds = group.getStoreIds().split(",");
                    for(String s:storeIds){
                        if (StringUtils.isNotEmpty(s)){
                            ids.add(Long.parseLong(s));
                        }
                    }
                    if (ids.size()>0){
                        orderInfo.setStoreIds(ids);
                    }
                }
            }
        }
        OrderInfo rst = orderInfoService.sumQueryList(orderInfo);
        if (rst != null && rst.getPayAmount() != null){
            return AjaxResult.success(MoneyUtils.changeF2Y(rst.getPayAmount()));
        }else{
            return AjaxResult.success("0");
        }
    }

    /**
     * 导出订单子列表
     */
    @PreAuthorize(hasPermi = "order:info:export")
    @Log(title = "订单子", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderInfo orderInfo) throws IOException {
        List<OrderExport> list = orderInfoService.exportList(orderInfo);
        ExcelUtil<OrderExport> util = new ExcelUtil<OrderExport>(OrderExport.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单子详细信息
     */
    @PreAuthorize(hasPermi = "order:info:query")
    @GetMapping(value = "/{orderUid}")
    public AjaxResult getInfo(@PathVariable("orderUid") Long orderUid) {
        return AjaxResult.success(orderInfoService.selectOrderInfoById(orderUid));
    }

    /**
     * 新增订单子
     */
    @PreAuthorize(hasPermi = "order:info:add")
    @Log(title = "订单子", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OrderInfo orderInfo) {
        return toAjax(orderInfoService.insertOrderInfo(orderInfo));
    }

    /**
     * 订单发货/补发/换货
     */
    @PreAuthorize(hasPermi = "order:info:edit")
    @Log(title = "订单子", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OrderInfo orderInfo) {
        return toAjax(orderInfoService.updateOrderInfo(orderInfo));
    }





    /**
     * 取消发货
     */
    @PreAuthorize(hasPermi = "order:info:edit")
    @Log(title = "订单子", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/cancelShip")
    public AjaxResult cancelShip(@RequestBody OrderQuery query) {
        return toAjax(orderInfoService.cancelShip(query));
    }



    /**
     * 订单添加备注
     */
    @PreAuthorize(hasPermi = "order:info:edit")
    @Log(title = "订单子", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/addRemark")
    public AjaxResult addRemark(@RequestBody OrderQuery query) {
        return AjaxResult.success(orderInfoService.addRemark(query));
    }

    /**
     * 开票
     */
    //@PreAuthorize(hasPermi = "order:info:edit")
    @Log(title = "订单子", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/addInvoice")
    public AjaxResult addInvoice(@RequestBody OrderInfo orderInfo) {
        if (orderInfo.getAmount() != null){
            orderInfo.setPayAmount(orderInfo.getAmount().multiply(new BigDecimal(100)).longValue());
        }
        return toAjax(orderInfoService.saveAdminOrderInfo(orderInfo));
    }


    @Log(title = "添加收款", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addPayInfo")
    public AjaxResult addPayInfo(@RequestBody OrderInfoItem orderInfoItem) {
        if (orderInfoItem.getAmount() != null){
            orderInfoItem.setPayAmount(orderInfoItem.getAmount().multiply(new BigDecimal(100)).longValue());
        }
        if (orderInfoItem.getOrderUid() == null){
            throw new RuntimeException("缺少订单ID");
        }
        OrderInfo orderInfo = orderInfoService.getById(orderInfoItem.getOrderUid());
        if (orderInfo == null || !orderInfo.getOrderStatus().equals(DataStatus.valid.getKey())){
            throw new RuntimeException("没有找到订单信息");
        }
        if (!orderInfo.getPlatSource().equals(PlatSourceEnum.manager.getKey())){
            throw new RuntimeException("非后台创建订单不能添加收款信息");
        }
        orderInfoItem.setPayByScore(0L);
        orderInfoItem.setOrderType(orderInfo.getOrderType());
        orderInfoItem.setCreateTime(new Date());
        orderInfoItem.setCreateUid(SecurityUtils.getUserId());
        orderInfoItem.setPayStatus("0");
        orderInfoItemService.save(orderInfoItem);
        return AjaxResult.success(orderInfoService.addPayInfo(orderInfo,orderInfoItem));
    }


}
